package com.qingxin.wuye.service;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import com.qingxin.sys.entity.LoginUser;
import com.qingxin.sys.entity.SysUser;
import com.qingxin.sys.mvc.SysError;
import com.qingxin.sys.service.BaseService;
import com.qingxin.sys.utils.StringUtils;
import com.qingxin.wuye.entity.SysUserGardenRel;
import com.qingxin.wuye.entity.WyGarden;

@Service
public class SysUserGardenRelService extends BaseService<SysUserGardenRel, String> {

	/**
	 * 添加用户小区关系
	 * @param userid
	 * @param gardenid
	 * @param loginUser
	 * @return
	 */
	public SysError addUserGardenRel(String userid, String gardenid, LoginUser loginUser){
		if(StringUtils.isEmpty(userid) || StringUtils.isEmpty(gardenid)){
			return null;
		}
		Object id = getByHql("select id from SysUserGardenRel where sysUser.userid=? and wyGarden.gardenid=?", userid, gardenid);
		if(id != null){
			return null;
		}
		SysUserGardenRel rel = new SysUserGardenRel(new WyGarden(gardenid), new SysUser(userid), loginUser.getUsername(), new Date());
		this.save(rel);
		return null;
	}
	
	
	/**
	 * 设置用户的小区查看权限
	 * @param userid
	 * @param gardenids
	 * @param loginUser
	 * @return
	 */
	public SysError saveUserGardenRels(String userid, String[] gardenids, LoginUser loginUser){
		if(StringUtils.isEmpty(userid)){
			return null;
		}
		//删除现有关联
		deleteByUserid(userid);
		
		if(gardenids==null || gardenids.length==0){
			return null;
		}
		
		Date now = new Date();
		String createBy = loginUser.getLogin_name();
		
		for(String gardenid : gardenids){
			SysUserGardenRel rel = new SysUserGardenRel(new WyGarden(gardenid), new SysUser(userid), createBy, now);
			this.save(rel);
		}
		
		return null;
	}
	
	
	/**
	 * 获取指定用户关联的小区id集合
	 * @param userid
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Set<String> getUserGardenids(String userid){
		Set<String> set = new HashSet<>();
		if(StringUtils.isEmpty(userid) ){			
			return set;
		}
		
		List<String> list = listByHql("select wyGarden.gardenid from SysUserGardenRel where sysUser.userid=?", userid);
		if(list != null){
			set.addAll(list);
		}
		return set;
	}
	
	
	/**
	 * 删除用户小区关联关系
	 * @param userid
	 * @return
	 */
	public SysError deleteByUserid(String userid){
		deleteByHql("delete from SysUserGardenRel where sysUser.userid=?", userid);
		return null;
	}
	
}
